package com.example.springdemo.controller;
/*
  @ClassName StaticHtml
 * @Description TODO
 * @author Wenyi Luo
 * @date 22/2/25 14:31
 * @version: 1.0
 */

import cn.hutool.core.util.IdUtil;
import com.example.springdemo.Utils.LogFileName;
import com.example.springdemo.Utils.LoggerUtils;
import com.example.springdemo.domain.HelloWorld;
import com.example.springdemo.domain.JsonData;
import com.example.springdemo.entity.Param;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.slf4j.Logger;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


@RestController
public class StaticHtml {
    Logger USER = LoggerUtils.logger(LogFileName.USER);
    @Resource
    private SpringTemplateEngine templateEngine;
    @Resource
    HelloWorld helloWorld;
    @Resource
    JsonData jsonData;

    @GetMapping("process")
    public HelloWorld process(@RequestBody Param jsonParam) throws IOException {
        System.out.println(jsonParam.toString());
        Context context = new Context();
        context.setVariable("name", jsonParam.getName());
//        File file=new File("D:"+ File.separator + "HTML");
//        if (!file.getParentFile().exists()) { //父路径不存在
//            file.getParentFile().mkdirs(); //创建父路径
//        }
        String fileName = IdUtil.objectId() + ".html";
        ApplicationHome home=new ApplicationHome(getClass());
        File path = home.getSource();
        File upload = new File(path.getAbsolutePath(), "static/html/");
        if (!upload.exists()) {
            upload.mkdirs();
            USER.info(upload.getAbsolutePath());
            //在开发测试模式时，得到地址为：{项目跟目录}/target/static/images/upload/
            //在打成jar正式发布时，得到的地址为:{发布jar包目录}/static/images/upload/
        }

        FileWriter fileWriter = new FileWriter(upload.getAbsolutePath() + fileName);
        templateEngine.process("world.html", context, fileWriter);
        helloWorld.setState(1);
        helloWorld.setMsg("页面生成功");
        jsonData.setContent("http://www.baidu.com");
        helloWorld.setData(jsonData);
        return helloWorld;
    }
}
